import json
from datetime import datetime
from typing import Optional

from configs.constants import constants
from .base_model import BaseModel

class CodeGenerationRecord(BaseModel):

    def __init__(self):
        self.id: Optional[int] = None
        self.module_id: str = ""
        self.module_name: str = ""
        self.data_dictionary: Optional[dict] = None
        self.original_pseudo_code: Optional[str] = None
        self.normalized_intermediate_1: Optional[str] = None
        self.normalized_intermediate_2: Optional[str] = None
        self.normalized_intermediate_3: Optional[str] = None
        self.normalized_intermediate_4: Optional[str] = None
        self.normalized_intermediate_5: Optional[str] = None
        self.normalized_intermediate_6: Optional[str] = None
        self.normalized_pseudo_code: Optional[str] = None
        self.c_code_status: int = constants.CCodeStatus.NOT_GENERATED
        self.c_code_error: Optional[str] = None
        self.generated_c_code: Optional[str] = None
        self.plugin_version: Optional[str] = None
        self.invocation_method: int = constants.InvocationMethodType.PUBLIC
        self.create_time: Optional[datetime] = None
        self.update_time: Optional[datetime] = None

    def to_dict(self, include_id=False) -> dict:
        data = {
            "module_id": self.module_id,
            "module_name": self.module_name,
            "data_dictionary": json.dumps(self.data_dictionary),
            "original_pseudo_code": self.original_pseudo_code,
            "normalized_intermediate_1": self.normalized_intermediate_1,
            "normalized_intermediate_2": self.normalized_intermediate_2,
            "normalized_intermediate_3": self.normalized_intermediate_3,
            "normalized_intermediate_4": self.normalized_intermediate_4,
            "normalized_intermediate_5": self.normalized_intermediate_5,
            "normalized_intermediate_6": self.normalized_intermediate_6,
            "normalized_pseudo_code": self.normalized_pseudo_code,
            "c_code_status": self.c_code_status,
            "c_code_error": self.c_code_error,
            "generated_c_code": self.generated_c_code,
            "plugin_version": self.plugin_version,
            "invocation_method": self.invocation_method,
        }
        if include_id and self.id:
            data["id"] = self.id
        return data

    @classmethod
    def from_dict(cls, data: dict):
        record = cls()
        for key, value in data.items():
            if hasattr(record, key):
                if key == "data_dictionary":
                    try:
                        setattr(record, key, json.loads(value) if value else None)
                    except json.JSONDecodeError:
                        setattr(record, key, None)
                else:
                    setattr(record, key, value)
        return record